// Main entry point for xg game.

include('asteroid');
include('blackhole');
include('entity');
include('game');
include('sound');
include('spacebackdrop')
include('spaceship');
include('graphics.director');
include('graphics.spritenode');

var cool_beans;

var dead = false;
var ship;

function handleMouseMove(x, y) {
}

function handleMouseDown(x, y) {
}

function handleMouseUp(x, y) {
  x -= director.layer("main").x;
  y -= director.layer("main").y;
//  sound.lazer.play();
  var bh = new BlackHole(x, y);
  game.addBlackHole(bh);
  setTimeout(function() {
    game.deleteBlackHole(bh);
  }, 2000);
}

function registerMouseHandler(fn) {
  return function(e) {
    var x = e.pageX - canvas.offsetLeft;
    var y = e.pageY - canvas.offsetTop;
    fn(x, y);
  };
}

function startPhysicsTimer() {
  setInterval(function() {
    game.stepPhysics();
  }, 1000 / 30);
}

function init() {
  canvas = document.getElementById("main-canvas");
  canvas.onmousemove = registerMouseHandler(handleMouseMove);
  canvas.onmousedown = registerMouseHandler(handleMouseDown);
  canvas.onmouseup = registerMouseHandler(handleMouseUp);

  window.sound = new SoundManager;
  window.game = new Game(canvas);
  window.director = new graphics.Director(canvas);

  director.start();
  game.start();
  director.addLayer("hud", -100);
  director.addLayer("main", 0);
  director.addLayer("backdrop", 100);

  var backdrop = new SpaceBackDrop();
  director.layer("backdrop").addChild(backdrop);

  ship = new SpaceShip();
  ship.register('shipDestroyed', function() {
    window.director.writeToScreen('Game Over!');
    document.getElementById('txt').innerHTML = "Game Over!";
    game.over();
  });
  director.layer("main").addChild(ship);
  game.addEntity(ship);

  var layerMain = director.layer("main");
  director.register('willStep', function() {
    layerMain.x = -ship.x + canvas.width/2;
    layerMain.y = -ship.y + canvas.height/2;
  });
  startPhysicsTimer();
  
  for(var i = 0; i < 15; i++) {
    var a = new Asteroid(
      Math.random() * 1000 - 500,
      Math.random() * 1000 - 500,
      Math.random() * 50 + 10);
    director.layer("main").addChild(a);
    game.addEntity(a);
  }
}

function screenshot() {
  var canvas = document.getElementById("main-canvas");
  window.open(canvas.toDataURL('image/png'));
}
